﻿from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib import auth
from django.contrib.auth.decorators import login_required
import time
import models, dbcore
#from django.utils.translation import ugettext_lazy as _
from utils import getLocalizedTemplate

def gotoPrifile(user, limit=1):
	return HttpResponseRedirect("/user/%s/%s" % (user.username, limit))

def gohome():
	return HttpResponseRedirect("/")

def index(request, *callback_args):
	return render_to_response(getLocalizedTemplate(request, "index.html"), locals())
	
def localize(request):
	return render_to_response(getLocalizedTemplate(request, "localize.html"), locals())

@login_required
def home(request):
	return gotoPrifile(request.user)	

def logout(request):
	auth.logout(request)
	return gohome()

def my(request, userName, limit, message=""):
	if not limit: limit = "1"
	user = request.user
	history = dbcore.userLocations(userName, limit)
	counters = ['1', '10', '15', '20', '50', '100']
	message = request.session.get("message", "")
	request.session["message"] = ""
	provider = request.GET.get('provider', 'yandex')
	providerTemplate = "maps/%s.html" % provider
	return render_to_response("my.html", locals())
	
@login_required
def live(request):
	return render_to_response("live.html", locals())	

def how(request):
	return render_to_response(getLocalizedTemplate(request, "how.html"), locals())

def download(request):
	return render_to_response(getLocalizedTemplate(request, "download.html"), locals())

@login_required
def addLocation(request):
	user = request.user
	lon = request.POST['longitude']
	lat = request.POST['latitude']
	speed = request.POST.get('speed', None)
	limit = request.POST.get('limit', 1)
	dbcore.addLocation(user, lon, lat, speed, time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
	return gotoPrifile(user, limit)

def add(request):
	username = request.POST['username']
	password = request.POST['password']

	user = auth.authenticate(username=username, password=password)
	if user is not None and user.is_active:
		lon = request.POST['longitude']
		lat = request.POST['latitude']
		speed = request.POST.get('speed', None)
		updated = request.POST['time']
		dbcore.addLocation(user, lon, lat, speed, updated)
		return HttpResponse("0")
	else: return HttpResponse("-1")

@login_required
def deleteLocation(request):
	user = request.user
	toDelete = []
	for key in request.POST.keys():
		if key.startswith("select"):
			toDelete.append(int(key.replace("select", "")))
	res = dbcore.deleteLocations(user, toDelete)
	limit = request.POST.get("limit", 1)
	request.session["message"] = _(u"Record deleted: %s") % res
	return HttpResponseRedirect("/user/%s/%s" % (user.username, limit))

def error():
	return HttpResponse("error")